import { Button, Flex } from "antd";
import React from "react";
import { runProg } from "../service/run";
import { dialog, fs } from "@tauri-apps/api";
import { simpleReq } from "../service/service";
import { cmd } from "../service/proto";
import { ByteView, Uint16, Uint32 } from "../service/codec";
import { Md5 } from "ts-md5";


export const Ota: React.FC = () => {

    const onClickUpgrade = async () => {
        runProg('更新', async (d) => {
            const path = await dialog.open({
                title: '打开升级文件',
                multiple: false,
                filters: [{
                    name: 'bin文件',
                    extensions: ["bin"]
                }]
            });
            if (path == null) {
                throw '文件没有选择'
            }
            const file = await fs.readBinaryFile(path as string);
            d.prog('文件打开成功开始升级');
            await simpleReq(cmd.OTA_START, [new Uint32(file.length)], []);
            let pkgId = 0;
            for (let index = 0; index < file.length; ) {
                let n = file.length - index;
                if (n > 240) {
                    n = 240;
                }
                const bw = new ByteView(file, index, n);
                await simpleReq(cmd.OTA_TRANSLATE, [new Uint16(pkgId), bw], []);
                d.prog(`进度:${ Math.floor( index * 100 / file.length ) }%`);
                index += n;
                pkgId += 1;
            }
            const m = new Md5();
            m.appendByteArray(file);
            const md5 = m.end(true) as Int32Array;
            const bw = new ByteView( new Uint8Array(md5.buffer), 0, 16 );
            await simpleReq(cmd.OTA_COMPLETE, [bw], []);
            d.prog('完成');
        });
    };

    return (
        <Flex className="card" vertical={true} gap={5}>
            <label style={{alignSelf: 'center'}}>软件更新</label>
            <Button onClick={onClickUpgrade} type={"primary"}>更新</Button>
        </Flex>
    )
}
